﻿namespace com.game.module.WiFiPvP
{
    using com.game;
    using com.game.basic;
    using com.game.basic.events;
    using com.game.consts;
    using com.game.data;
    using com.game.manager;
    using com.game.module.core;
    using com.game.module.fight.arpg;
    using com.game.module.hud;
    using com.game.module.map;
    using com.game.utils;
    using com.game.vo;
    using com.net.wifi_pvp;
    using com.u3d.bases.ai;
    using com.u3d.bases.display;
    using com.u3d.bases.display.character;
    using Proto;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Runtime.CompilerServices;
    using UnityEngine;
    using UnityLog;

    public class WifiPvpManager
    {
        private bool _countdownMutex = true;
        private readonly Dictionary<ActionDisplay, float> _countingDownDic = new Dictionary<ActionDisplay, float>();
        private readonly Dictionary<ActionDisplay, float> _countingDownDic2 = new Dictionary<ActionDisplay, float>();
        private IDictionary<int, List<Vector3>> _dictPathPosList = new Dictionary<int, List<Vector3>>();
        private int _enemyDead;
        private readonly IDictionary<ActionDisplay, FightCounter> _enemyDic = new Dictionary<ActionDisplay, FightCounter>();
        private int _enemyTotalKill;
        private bool _isEndMsgSent;
        private bool _isInitialized;
        private bool _isMaster;
        private bool _isPvpBaseReady;
        private bool _isRebornToSping = true;
        private MonsterDisplay _myBaseDisplay;
        private readonly IDictionary<ActionDisplay, FightCounter> _playerDic = new Dictionary<ActionDisplay, FightCounter>();
        private BaseRoleVo _pvpBaseVo;
        private float _tick;
        private int _totalDead;
        private int _totalKill;
        private readonly IList<MonsterDisplay> _towerList = new List<MonsterDisplay>();
        [CompilerGenerated]
        private static Func<MonsterDisplay, TowerAiController> <>f__am$cache19;
        [CompilerGenerated]
        private static Func<TowerAiController, bool> <>f__am$cache1A;
        [CompilerGenerated]
        private static vp_Timer.Callback <>f__am$cache1B;
        public static readonly WifiPvpManager Instance;

        static WifiPvpManager()
        {
            if (Instance == null)
            {
            }
            Instance = new WifiPvpManager();
        }

        private WifiPvpManager()
        {
            GlobalAPI.facade.Add(15, new NoticeListener(this.SaveMyBaseAndTower));
            GlobalAPI.facade.Add(0x16, new NoticeListener(this.SyncSummon));
        }

        public void AddEnemy(PlayerDisplay display)
        {
            if (display != null)
            {
                this._enemyDic.Add(display);
                Singleton<BattleTopRightView>.Instance.AddPlayer(display, false);
            }
            else
            {
                Debug.LogWarning("监听Enemy为null");
            }
        }

        public void AddEnemyBase(MonsterDisplay display)
        {
            if ((display != null) && !display.GetMeVoByType<BaseRoleVo>().IsEmptyHp)
            {
                MonsterVo meVoByType = display.GetMeVoByType<MonsterVo>();
                Singleton<BattleTopRightView>.Instance.AddTowerOrBase(display, meVoByType.MonsterVO.type, false);
            }
        }

        public void AddEnemyTower(MonsterDisplay tower)
        {
            if (((tower == null) || tower.GetMeVoByType<BaseRoleVo>().IsEmptyHp) || (tower.GetMeVoByType<MonsterVo>().MonsterVO.type != 3))
            {
                Debug.LogError("注册的塔有问题");
            }
            else
            {
                MonsterVo meVoByType = tower.GetMeVoByType<MonsterVo>();
                Singleton<BattleTopRightView>.Instance.AddTowerOrBase(tower, meVoByType.MonsterVO.type, false);
            }
        }

        public void AddMyBase(MonsterDisplay display)
        {
            if ((display == null) || display.GetMeVoByType<BaseRoleVo>().IsEmptyHp)
            {
                Debug.LogError("注册的基地有问题");
                this._myBaseDisplay = null;
                this._pvpBaseVo = null;
            }
            else
            {
                MonsterVo meVoByType = display.GetMeVoByType<MonsterVo>();
                this._myBaseDisplay = display;
                this._isPvpBaseReady = true;
                this._pvpBaseVo = meVoByType;
                Singleton<BattleTopRightView>.Instance.AddTowerOrBase(display, meVoByType.MonsterVO.type, true);
            }
        }

        public void AddMyTower(MonsterDisplay tower)
        {
            if (((tower == null) || tower.GetMeVoByType<BaseRoleVo>().IsEmptyHp) || (tower.GetMeVoByType<MonsterVo>().MonsterVO.type != 3))
            {
                Debug.LogError("注册的塔有问题");
            }
            else
            {
                this._towerList.Add(tower);
                MonsterVo meVoByType = tower.GetMeVoByType<MonsterVo>();
                Singleton<BattleTopRightView>.Instance.AddTowerOrBase(tower, meVoByType.MonsterVO.type, true);
            }
        }

        public void AddPlayer(PlayerDisplay display)
        {
            if (display != null)
            {
                this._playerDic.Add(display);
                Singleton<BattleTopRightView>.Instance.AddPlayer(display, true);
            }
            else
            {
                Debug.LogWarning("监听Player为null");
            }
        }

        private void Clear()
        {
            this._enemyDic.Clear();
            this._playerDic.Clear();
            this._towerList.Clear();
            this._dictPathPosList.Clear();
            this._tick = 0f;
            this._pvpBaseVo = null;
            this._myBaseDisplay = null;
            this._isMaster = false;
            this._isEndMsgSent = false;
            this._isPvpBaseReady = false;
            this._isInitialized = false;
            this.PvpTemplate = null;
            this.EnemyTotalKill = this._enemyDead = 0;
            this.TotalKill = this._totalDead = 0;
            this.EnemySoul = 0;
            Vector3 vector2 = new Vector3();
            this.EnemyBasePos = vector2;
            this.MySpringPos = vector2;
            this.MyBasePos = vector2;
        }

        private void ClearAfterEnd()
        {
            this.Clear();
            MeVo.instance.ClearSoul();
            PrivateMgr.Instance.Clear();
            BattleObjectMgr.Instance.Clear();
            Singleton<WifiPvpMode>.Instance.IsMaster = false;
            Singleton<WifiPvpMode>.Instance.ClearWhenEndPVP();
            Singleton<WifiPvpControl>.Instance.ClearGeneralDicWhenQuitPVP();
        }

        public void DisableAllAi()
        {
            AiManagerBase.StopAllAi();
        }

        private static Vector3 DivideWith1000(Vector3 vec)
        {
            return StringUtils.DivideWith1000(vec);
        }

        private void DoMyHeroReborn(bool isToSpring, ulong id, uint soul, bool isAiEnable)
        {
            <DoMyHeroReborn>c__AnonStoreyF1 yf = new <DoMyHeroReborn>c__AnonStoreyF1 {
                id = id
            };
            PlayerDisplay play = AppMap.Instance.SelfplayerList.FirstOrDefault<PlayerDisplay>(new Func<PlayerDisplay, bool>(yf.<>m__CC));
            if (play == null)
            {
                Debug.LogError("复活时取不到display");
            }
            else
            {
                Debug.Log("我方单位复活");
                Vector3 vec = !isToSpring ? play.GoBase.transform.position : (!this._isMaster ? StringUtils.StringToVector3(this.PvpTemplate.slave_born_pos) : StringUtils.StringToVector3(this.PvpTemplate.master_born_pos));
                vec = DivideWith1000(vec);
                Singleton<WifiPvpControl>.Instance.DoReborn(play, vec);
                Singleton<WifiPvpMode>.Instance.Relive(yf.id, vec);
                play.Controller.buffController.Reborn();
                play.Controller.AiController.SetAi((play != AppMap.Instance.me) || isAiEnable);
                Debug.Log("复活时加上血条");
                Log.AI(null, "AddBloodBar For Relive Object " + play);
                BaseRoleVo vo = play.GetVo();
                HudView.Instance.AddPlayerHealthBarWhenEmpty(play);
                play.Controller.GoHp.GetComponent<UpdateHpBar>().SetHp(vo.Hp, vo.CurHp, false);
            }
        }

        private void DoSetupBattleObject(bool isMaster)
        {
            if (isMaster)
            {
                BattleObjectMgr.Instance.InitAsMaster(this.PvpTemplate.battle_object_list);
            }
            else
            {
                BattleObjectMgr.Instance.InitAsSlave();
            }
        }

        private void DoSetupPath(bool isMaster)
        {
            string str = !isMaster ? this.PvpTemplate.slave_private_path_list : this.PvpTemplate.master_private_path_list;
            Debug.LogWarning("我方小兵路点:" + str);
            this._dictPathPosList = StringUtils.SplitStringToPathPosList(str);
        }

        private void DoSetupPos(bool isMaster)
        {
            if (isMaster)
            {
                this.MyBasePos = DivideWith1000(StringUtils.StringToVector3(this.PvpTemplate.master_base_pos));
                this.MySpringPos = DivideWith1000(StringUtils.StringToVector3(this.PvpTemplate.master_spring_pos));
                this.EnemyBasePos = DivideWith1000(StringUtils.StringToVector3(this.PvpTemplate.slave_base_pos));
            }
            else
            {
                this.MyBasePos = DivideWith1000(StringUtils.StringToVector3(this.PvpTemplate.slave_base_pos));
                this.MySpringPos = DivideWith1000(StringUtils.StringToVector3(this.PvpTemplate.slave_spring_pos));
                this.EnemyBasePos = DivideWith1000(StringUtils.StringToVector3(this.PvpTemplate.master_base_pos));
            }
        }

        private void DoSetupPrivate(bool isMaster)
        {
            string privateString = !isMaster ? this.PvpTemplate.slave_private_list : this.PvpTemplate.master_private_list;
            PrivateMgr.Instance.Init(privateString);
        }

        public void EnemyIncreaseDeadCount(ActionDisplay player)
        {
            if (this._enemyDic.ContainsKey(player))
            {
                this._enemyDic[player].AddDeadCount();
                this._enemyDead++;
            }
        }

        public void EnemyIncreaseKillCount(ActionDisplay player)
        {
            Log.AI(player, " EnemyIncreaseKillCount ");
            if (this._enemyDic.ContainsKey(player))
            {
                this._enemyDic[player].AddKillCount();
                this.EnemyTotalKill++;
            }
            else
            {
                Debug.LogWarning("非敌方杀人");
            }
        }

        public void Enter(uint pvpId, bool isMaster)
        {
            this.Clear();
            WifiLAN.Instance.EndFlag = WifiPvpConst.PVPEndState.started;
            this.Setup(BaseDataMgr.instance.GetWifiPvpVo(pvpId), isMaster);
        }

        ~WifiPvpManager()
        {
            GlobalAPI.facade.Remove(15, new NoticeListener(this.SaveMyBaseAndTower));
            GlobalAPI.facade.Remove(0x16, new NoticeListener(this.SyncSummon));
        }

        private Dictionary<ActionDisplay, float> GetCountDownDic()
        {
            return (!this._countdownMutex ? this._countingDownDic2 : this._countingDownDic);
        }

        public FightCounter GetPvpStaticByTid(ulong id, bool isMe)
        {
            <GetPvpStaticByTid>c__AnonStoreyEF yef = new <GetPvpStaticByTid>c__AnonStoreyEF {
                id = id
            };
            IDictionary<ActionDisplay, FightCounter> dictionary = !isMe ? this._enemyDic : this._playerDic;
            ActionDisplay display = dictionary.Keys.FirstOrDefault<ActionDisplay>(new Func<ActionDisplay, bool>(yef.<>m__C8));
            return ((display == null) ? null : dictionary[display]);
        }

        private float GetReliveTime()
        {
            return Mathf.Min((float) ((MeVo.instance.soul * 0.3f) + 15f), (float) 30f);
        }

        public int GetTimecost()
        {
            return Mathf.CeilToInt(this._tick);
        }

        public void GiveUp()
        {
            WifiLAN.Instance.HandlePressChangeButton();
        }

        public void HandleCloseEndView()
        {
            this.ClearAfterEnd();
        }

        private void HideUI()
        {
        }

        public void IncreaseDeadCount(ActionDisplay player)
        {
            if (this._playerDic.ContainsKey(player))
            {
                this._playerDic[player].AddDeadCount();
                this._totalDead++;
            }
        }

        public void IncreaseKillCount(ActionDisplay player)
        {
            if (this._playerDic.ContainsKey(player))
            {
                this._playerDic[player].AddKillCount();
                this.TotalKill++;
            }
            else
            {
                Debug.LogWarning("非我方英雄杀人");
            }
        }

        private void InitUI()
        {
        }

        public static void LoadingFinished()
        {
            if (<>f__am$cache1B == null)
            {
                <>f__am$cache1B = () => WifiLAN.Instance.PVPLoadingFinish();
            }
            vp_Timer.In(0.25f, <>f__am$cache1B, null);
        }

        public void MyHeroBeAttackByEnemyHero(MeDisplay myhero, PlayerDisplay enemy)
        {
            if ((myhero != null) && (enemy != null))
            {
                if (<>f__am$cache19 == null)
                {
                    <>f__am$cache19 = md => md.Controller.AiController as TowerAiController;
                }
                if (<>f__am$cache1A == null)
                {
                    <>f__am$cache1A = ai => ai != null;
                }
                IEnumerator<TowerAiController> enumerator = this._towerList.Select<MonsterDisplay, TowerAiController>(<>f__am$cache19).Where<TowerAiController>(<>f__am$cache1A).GetEnumerator();
                try
                {
                    while (enumerator.MoveNext())
                    {
                        TowerAiController current = enumerator.Current;
                        Debug.Log("我方英雄被攻击, 塔尝试攻击敌方英雄");
                        current.TurnToMyHerosEnemy(enemy);
                    }
                }
                finally
                {
                    if (enumerator == null)
                    {
                    }
                    enumerator.Dispose();
                }
            }
        }

        public void MyHeroDie(MeDisplay myhero)
        {
            if (this._playerDic.ContainsKey(myhero))
            {
                <MyHeroDie>c__AnonStoreyF0 yf = new <MyHeroDie>c__AnonStoreyF0 {
                    <>f__this = this
                };
                Debug.Log("我方英雄被打死");
                yf.lastAiEnable = myhero.Controller.AiController.IsAiEnable;
                yf.player = myhero.GetMeVoByType<PlayerVo>();
                SysSoulVo dataByTypeAndId = BaseDataMgr.instance.GetDataByTypeAndId<SysSoulVo>("SysSoulVo", MeVo.instance.soul);
                float reliveTime = this.GetReliveTime();
                Log.AI(null, "SetReliveTime " + reliveTime);
                vp_Timer.In(reliveTime, new vp_Timer.Callback(yf.<>m__CB), null);
                if (this.GetCountDownDic().ContainsKey(myhero))
                {
                    this.GetCountDownDic().Remove(myhero);
                }
                this.GetCountDownDic().Add(myhero, reliveTime);
                Singleton<WifiPvpMode>.Instance.Dead(yf.player.Id, myhero.GoBase.transform.position);
            }
            else
            {
                Debug.LogWarning("非我方英雄死亡!");
            }
        }

        private void MyHeroReborn(ulong id, uint soul, bool isAiEnable)
        {
            if (AppMap.Instance.IsInWifiPVP)
            {
                this.DoMyHeroReborn(this._isRebornToSping, id, soul, isAiEnable);
            }
            else
            {
                Debug.Log("我方英雄复活, 但已经不在PVP中");
            }
        }

        public List<Vector3> MyPath(int groupIdx)
        {
            if (this._dictPathPosList.ContainsKey(groupIdx))
            {
                return this._dictPathPosList[groupIdx];
            }
            Debug.LogError("小兵查询自身路点, 不存在, groupIdx =" + groupIdx);
            return null;
        }

        private static void PrintLeftTimeToReborn(float leftTime)
        {
            Debug.Log("剩余复活时间: " + leftTime);
        }

        public void RegisterTowerOrBase(BaseDisplay display)
        {
        }

        public void RemoveEnemyTowerOrBase(MonsterDisplay tower)
        {
            if (tower != null)
            {
                switch (tower.GetMeVoByType<MonsterVo>().MonsterVO.type)
                {
                    case 3:
                        Singleton<BattleTopRightView>.Instance.RemoveTowerOrBase(tower, false);
                        break;

                    case 5:
                        Singleton<BattleTopRightView>.Instance.RemoveTowerOrBase(tower, false);
                        break;
                }
            }
        }

        public void RemoveMyTowerOrBase(MonsterDisplay tower)
        {
            if (tower != null)
            {
                switch (tower.GetMeVoByType<MonsterVo>().MonsterVO.type)
                {
                    case 3:
                        Singleton<BattleTopRightView>.Instance.RemoveTowerOrBase(tower, true);
                        this._towerList.Remove(tower);
                        break;

                    case 5:
                        Singleton<BattleTopRightView>.Instance.RemoveTowerOrBase(tower, true);
                        break;
                }
            }
        }

        private void SaveMyBaseAndTower(int type, int v1, int v2, object data)
        {
            MapSightMsg_4_2 g__ = data as MapSightMsg_4_2;
            if ((g__ != null) && AppMap.Instance.IsInWifiPVP)
            {
                Singleton<WifiPvpMode>.Instance.MyBaseAndTower = g__.monsEnter;
            }
        }

        private void Setup(SysWifiPvpVo vo, bool isMaster)
        {
            if (vo == null)
            {
                Debug.LogError("取不到Wifi PVP模板表");
            }
            else
            {
                this._isInitialized = true;
                this.PvpTemplate = vo;
                this._isMaster = isMaster;
                this._tick = 0f;
                this.DoSetupPos(isMaster);
                this.DoSetupPrivate(isMaster);
                this.DoSetupPath(isMaster);
                this.DoSetupBattleObject(isMaster);
                this.InitUI();
            }
        }

        public void SyncBattleObjectToOthers(List<PBattleObject> list)
        {
            if (AppMap.Instance.IsInWifiPVP && this._isMaster)
            {
                Log.AI(null, "Sync Battle Object To Others " + list.Count);
                Singleton<WifiPvpMode>.Instance.SyncBattleObjectToOthers(list);
            }
        }

        private void SyncSummon(int type, int v1, int v2, object data)
        {
            MapMonBornSightMsg_4_23 msg = data as MapMonBornSightMsg_4_23;
            if ((msg != null) && AppMap.Instance.IsInWifiPVP)
            {
                Singleton<WifiPvpMode>.Instance.SyncAddSummon(msg);
            }
        }

        public void Update()
        {
            if (this._isInitialized && this._isPvpBaseReady)
            {
                this._tick += Time.deltaTime;
                if (((this._myBaseDisplay != null) && AppMap.Instance.IsInWifiPVP) && !this._isEndMsgSent)
                {
                    if (this._pvpBaseVo.IsEmptyHp)
                    {
                        Debug.Log("我方基地被摧毁, 我方战败");
                        this._isEndMsgSent = true;
                        Singleton<WifiPvpMode>.Instance.PVPEndAndTellOther(WifiPvpConst.PVPEndState.fail, false);
                    }
                    this.UpdateCountingDown();
                }
            }
        }

        public void UpdateBattleView()
        {
            int master = !this._isMaster ? this.EnemyTotalKill : this.TotalKill;
            int slave = !this._isMaster ? this.TotalKill : this.EnemyTotalKill;
            if (this._isInitialized)
            {
                Singleton<BattleTopRightView>.Instance.UpdateStat(master, slave);
            }
        }

        private void UpdateCountingDown()
        {
            Dictionary<ActionDisplay, float> countDownDic = this.GetCountDownDic();
            Dictionary<ActionDisplay, float> dictionary2 = !this._countdownMutex ? this._countingDownDic : this._countingDownDic2;
            dictionary2.Clear();
            foreach (ActionDisplay display in countDownDic.Keys)
            {
                if (countDownDic[display] > 0f)
                {
                    float num = countDownDic[display] - Time.deltaTime;
                    dictionary2.Add(display, num);
                }
            }
            this._countdownMutex = !this._countdownMutex;
        }

        public void UpdateEnemySoul(uint p)
        {
            this.EnemySoul = p;
        }

        public Vector3 EnemyBasePos { get; private set; }

        public uint EnemySoul { get; set; }

        public int EnemyTotalKill
        {
            get
            {
                return this._enemyTotalKill;
            }
            private set
            {
                this._enemyTotalKill = value;
                this.UpdateBattleView();
            }
        }

        public Vector3 MyBasePos { get; set; }

        public Vector3 MySpringPos { get; private set; }

        public SysWifiPvpVo PvpTemplate { get; private set; }

        public int TotalKill
        {
            get
            {
                return this._totalKill;
            }
            private set
            {
                this._totalKill = value;
                this.UpdateBattleView();
            }
        }

        [CompilerGenerated]
        private sealed class <DoMyHeroReborn>c__AnonStoreyF1
        {
            internal ulong id;

            internal bool <>m__CC(PlayerDisplay x)
            {
                return (x.GetVo().Id == this.id);
            }
        }

        [CompilerGenerated]
        private sealed class <GetPvpStaticByTid>c__AnonStoreyEF
        {
            internal ulong id;

            internal bool <>m__C8(ActionDisplay x)
            {
                return (x.GetVo().Id == this.id);
            }
        }

        [CompilerGenerated]
        private sealed class <MyHeroDie>c__AnonStoreyF0
        {
            internal WifiPvpManager <>f__this;
            internal bool lastAiEnable;
            internal PlayerVo player;

            internal void <>m__CB()
            {
                this.<>f__this.MyHeroReborn(this.player.Id, MeVo.instance.soul, this.lastAiEnable);
            }
        }
    }
}

